package com.ycfmedical.bed.base;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.R;
import com.ycfmedical.bed.widgets.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.droidlover.xdroidmvp.base.XFragmentAdapter;
import cn.droidlover.xdroidmvp.mvp.XFragment;

/**
 * Created by yf on 2017-03-31.
 * 所有页面均为tabs+fragments 所以抽象出来
 */

public abstract class BaseFragmentList extends XFragment<BasePresenter> {
    XFragmentAdapter mAdapter;
    @BindView(R.id.fragmentsTab)
    protected TabLayout fragmentsTab;
    @BindView(R.id.fragmentsViewPager)
    protected  NoScrollViewPager fragmentsViewPager;


    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    private String[] titles ;

    @Override
    public void initData(Bundle savedInstanceState) {
        titles= addTabTitle(titles);
        fragmentsTab.setTabGravity(TabLayout.GRAVITY_CENTER);
        fragmentsTab.setTabMode(TabLayout.GRAVITY_FILL);

        addFragmentList(fragmentList);
        initViewPager();
         initTab();
    }

    private void initTab() {
        int  tabCount=fragmentsTab.getTabCount();
        for (int i = 0; i <tabCount ; i++) {
            setTab(fragmentsTab.getTabAt(i));
        }
    }

    protected abstract void addFragmentList(List<Fragment> fragmentList);
    protected abstract String[] addTabTitle(String[] titles);

    @Override
    public int getLayoutId() {
        return R.layout.fragmentlist_base;
    }

    /**
     * 用getChildFragmentManager()可以解决页面卡顿的问题
     */
    private void initViewPager() {

        if (mAdapter == null) {
            mAdapter = new XFragmentAdapter(getChildFragmentManager(), fragmentList, titles);
        }
        fragmentsViewPager.setAdapter(mAdapter);

//        if(!getActivity().getSupportFragmentManager().executePendingTransactions()){
//
        fragmentsViewPager.setOffscreenPageLimit(fragmentList.size());
//        }
        fragmentsTab.setupWithViewPager(fragmentsViewPager);
    }
    /**
     * 自定义tabView
     */
    private void setTab(TabLayout.Tab tab ) {
        if (null != tab) {
            String title = tab.getText().toString();
            View view = getActivity().getLayoutInflater().inflate(R.layout.childtab_custom_view, null);
            TextView titleTV = (TextView) view.findViewById(R.id.tabTitle);
            titleTV.setText(title);
            tab.setCustomView(view);
        }
    }
    @Override
    public BasePresenter newP() {
        return null;
    }



}
